package top.rainbowecho.notify.domain.model.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.rainbowecho.notify.domain.model.sms.config.SmsConfiguration;

import java.util.Map;

/**
 * @author rainbow
 * @since 2020/4/8 13:31
 */
@Component
public class SmsSender {
    private SmsConfiguration smsConfiguration;

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setSmsConfiguration(SmsConfiguration smsConfiguration) {
        this.smsConfiguration = smsConfiguration;
    }

    /**
     * 发送注册短信消息
     *
     * @param param
     * @param phoneNumbers
     * @return
     * @throws JsonProcessingException
     */
    public String sendRegisterSms(Map<String, Object> param, String... phoneNumbers) throws JsonProcessingException {
        String regionId = this.smsConfiguration.getRegionId();
        String joinPhoneNumbers = String.join(",", phoneNumbers);
        String jsonParam = this.objectMapper.writeValueAsString(param);

        DefaultProfile profile = DefaultProfile.getProfile(regionId
                , this.smsConfiguration.getAccessKeyId(), this.smsConfiguration.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", joinPhoneNumbers);
        request.putQueryParameter("SignName", this.smsConfiguration.getSignName());
        request.putQueryParameter("TemplateCode", this.smsConfiguration.getTemplateCode());
        request.putQueryParameter("TemplateParam", jsonParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getData();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return StringUtils.EMPTY;
    }
}
